﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Templates_Upload : BaseTemplatePage
{
    public override Acms.Bll.Role.Roles[] AllowedRoles
    {
        get
        {
            return new Acms.Bll.Role.Roles[] { Acms.Bll.Role.Roles.Developer };
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        tree.NodeExpand += new Telerik.Web.UI.RadTreeViewEventHandler(tree_NodeExpand);
        tree.NodeClick += new Telerik.Web.UI.RadTreeViewEventHandler(tree_NodeClick);
        btnDownload.Click += new EventHandler(btnDownload_Click);
        if(!IsPostBack)
            DataBind();
    }

    void btnDownload_Click(object sender, EventArgs e)
    {
        //Create the XmlDocument
        Trace.IsEnabled = false;
        Response.ClearHeaders();
        Response.Clear();
        Response.ContentType = "text/xml";
        Response.AppendHeader("Content-Disposition", "attachment;filename=Templates.xml");

        Response.ContentType = "";
        System.Xml.XmlTextWriter xml = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
        xml.Formatting = System.Xml.Formatting.Indented;
        xml.WriteStartDocument();

        var templates = Acms.Bll.Template.GetAllBySiteId(AcmsContext.SiteId);
        var controlTypes = Acms.Bll.ControlType.GetAllBySiteId(AcmsContext.SiteId);
        xml.WriteStartElement("acms");
        xml.WriteStartElement("templates");
        foreach (var template in templates)
        {
            xml.WriteStartElement("template");
            xml.WriteAttributeString("name", template.Name);
            xml.WriteAttributeString("type", template.NodeType.ToString());

            xml.WriteStartElement("notes");
            xml.WriteCData(template.Notes);
            xml.WriteEndElement();

            xml.WriteStartElement("files");
            foreach (var file in Acms.Bll.TemplateFile.GetAllByTemplateId(template.Id))
            {
                xml.WriteStartElement("file");
                xml.WriteAttributeString("name", file.Name);
                xml.WriteAttributeString("path", file.Path);
                xml.WriteAttributeString("default", file.IsDefault ? "true" : "false");
                xml.WriteEndElement();
            }
            xml.WriteEndElement();

            xml.WriteStartElement("controls");
            foreach (var control in Acms.Bll.TemplateControl.GetAllByTemplateId(template.Id))
            {
                xml.WriteStartElement("control");
                xml.WriteAttributeString("name", control.Name);
                xml.WriteAttributeString("type", controlTypes.Where(x => x.Id == control.TypeId).Single().Name);
                xml.WriteStartElement("notes");
                xml.WriteCData(control.Notes);
                xml.WriteEndElement();
                xml.WriteEndElement();
            }
            xml.WriteEndElement();

            xml.WriteStartElement("children");
            foreach (var child in Acms.Bll.TemplateHierarchy.GetAllByParentId(template.Id))
            {
                xml.WriteStartElement("child");
                xml.WriteAttributeString("name", child.ChildName);
                xml.WriteEndElement();
            }
            xml.WriteEndElement();

            xml.WriteEndElement();
        }
        xml.WriteEndElement();
        xml.WriteEndElement();
        xml.WriteEndDocument();
        xml.Close();
        Response.End();
    }

    /// <summary>
    /// Adds string message to log
    /// </summary>
    /// <param name="message"></param>
    private void AddToLog(string message)
    {
        AddToLog(message, new object[0]);
    }

    /// <summary>
    /// Adds string message to log using string format
    /// </summary>
    /// <param name="message"></param>
    private void AddToLog(string message, params object[] args)
    {
        string tmp = string.Format(message, args);
        lblReport.Text = string.Concat(lblReport.Text, "<p>", tmp, "</p>");
    }

    /// <summary>
    /// Uploads settings from xml file
    /// </summary>
    /// <param name="path">mapped path to file</param>
    private void UploadSettings(string path)
    {
        AddToLog("Starting for {0}", path);
        System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(path);
        if (doc.Root.Element("controls") != null)
        {
            var controls = doc.Root.Element("controls").Elements("control");
            UploadControls(controls.ToList());
        }
        if (doc.Root.Element("templates") != null)
        {
            var templates = doc.Root.Element("templates").Elements("template");
            UploadTemplates(templates.ToList());
        }
    }

    private void UploadControls(List<System.Xml.Linq.XElement> controls)
    {
        AddToLog("{0} controls found", controls.Count);
        var current = Acms.Bll.ControlType.GetAllBySiteId(AcmsContext.SiteId);
        foreach (var control in controls)
        {
            var nameAttribute = control.Attribute("name");
            var frontEndAttribute = control.Attribute("frontEnd");
            var adminDisplayAttribute = control.Attribute("adminDisplay");
            var adminEditAttribute = control.Attribute("adminEdit");
            var notes = control.Value;

            if (nameAttribute == null)
            {
                AddToLog("No name attribute for control {0} found", controls.IndexOf(control));
            }
            if (frontEndAttribute == null)
            {
                AddToLog("No frontEnd attribute for control {0} found", controls.IndexOf(control));
            }
            if (adminDisplayAttribute == null)
            {
                AddToLog("No adminDisply attribute for control {0} found", controls.IndexOf(control));
            }
            if (adminEditAttribute == null)
            {
                AddToLog("No adminEdit attribute for control {0} found", controls.IndexOf(control));
            }
            
            if (nameAttribute != null && frontEndAttribute != null && adminDisplayAttribute != null && adminEditAttribute != null)
            {
                var save = false;
                var currentItem = current.Where(x => x.FrontEndControlType.Replace(" ", "") == frontEndAttribute.Value.Replace(" ", "")).FirstOrDefault();
                if (currentItem == null)
                {
                    save = true;
                    currentItem = Acms.Bll.ControlType.CreateInstance();
                }

                if (currentItem.Name != nameAttribute.Value)
                {
                    save = true;
                    currentItem.Name = nameAttribute.Value;
                }


                if (currentItem.FrontEndControlType != frontEndAttribute.Value)
                {
                    save = true;
                    currentItem.FrontEndControlType = frontEndAttribute.Value;
                }

                if (currentItem.AdminEditControlType != adminEditAttribute.Value)
                {
                    save = true;
                    currentItem.AdminEditControlType = adminEditAttribute.Value;
                }

                if (currentItem.AdminDisplayControlType != adminDisplayAttribute.Value)
                {
                    save = true;
                    currentItem.AdminDisplayControlType = adminDisplayAttribute.Value;
                }

                if (currentItem.Notes != notes)
                {
                    save = true;
                    currentItem.Notes = notes;
                }

                if (save)
                {
                    AddToLog("Saving Control Type {0}", nameAttribute.Value);
                    currentItem.Update();
                }
            }
        }
    }

    /// <summary>
    /// Uploads templates settings form xml template nodes
    /// </summary>
    /// <param name="templates"></param>
    private void UploadTemplates(IList<System.Xml.Linq.XElement> templates)
    {
        AddToLog("{0} templates found", templates.Count);
        var currentTemplates = Acms.Bll.Template.GetAllBySiteId(AcmsContext.SiteId);
        foreach (var template in templates)
        {
            var nameAttribute = template.Attribute("name");
            var typeAttribute = template.Attribute("type");
            var notes = template.Element("notes");
            if(nameAttribute == null || string.IsNullOrEmpty(nameAttribute.Value))
            {
                AddToLog("No name attribute for template {0} found", templates.IndexOf(template));
            }
            else
            {
                bool save = false;
                var acmsTemplate = currentTemplates.Where(x => x.Name == nameAttribute.Value).FirstOrDefault();
                if (acmsTemplate == null)
                {
                    AddToLog("Creating {0}", nameAttribute.Value);
                    acmsTemplate = Acms.Bll.Template.CreateInstance();
                    acmsTemplate.SiteId = AcmsContext.SiteId;
                    acmsTemplate.Name = nameAttribute.Value;
                    currentTemplates.Add(acmsTemplate);
                    save = true;
                }
                else
                {
                    AddToLog("Found {0}", nameAttribute.Value);
                }

                var acmsFiles = Acms.Bll.TemplateFile.GetAllByTemplateId(acmsTemplate.Id);
                var acmsControls = Acms.Bll.TemplateControl.GetAllByTemplateId(acmsTemplate.Id);

                acmsTemplate.BeginTransaction();

                if (notes != null && acmsTemplate.Notes != notes.Value)
                {
                    acmsTemplate.Notes = notes.Value;
                    save = true;
                }

                if(typeAttribute != null)
                {
                    Acms.Bll.Template.NodeTypes tmpType = acmsTemplate.NodeType;
                    try
                    {
                        tmpType = (Acms.Bll.Template.NodeTypes)Enum.Parse(typeof(Acms.Bll.Template.NodeTypes), typeAttribute.Value);
                    }
                    catch
                    {
                    }
                    if (acmsTemplate.NodeType != tmpType)
                    {
                        save = true;
                        acmsTemplate.NodeType = tmpType;
                    }
                }

                if (save)
                {
                    AddToLog("Saving {0}", nameAttribute.Value);
                    acmsTemplate.Update();
                }

                try
                {
                    UploadFilesSettings(template, acmsTemplate, acmsFiles);
                    UploadControlSettings(template, acmsTemplate, acmsControls, Acms.Bll.ControlType.GetAllBySiteId(AcmsContext.SiteId));
                }
                catch
                {
                    AddToLog("Rolling Back {0}", nameAttribute.Value);
                    acmsTemplate.RollbackTransaction();
                    throw;
                }
                finally
                {
                    if (acmsTemplate.TransactionKey != Guid.Empty)
                    {
                        AddToLog("Commmiting {0}", nameAttribute.Value);
                        acmsTemplate.CommitTransaction();
                    }
                }
            }
        }
        //Now do for Heireachy
        AddToLog("Processing Template Heirearcy");
        foreach (var template in templates)
        {
            var nameAttribute = template.Attribute("name");
            if(nameAttribute != null)
            {
                var acmsTemplate = currentTemplates.Where(x => x.Name == nameAttribute.Value).FirstOrDefault();
                acmsTemplate.BeginTransaction();
                try
                {
                    if (acmsTemplate != null)
                    {
                        var childrenElement = template.Element("children");
                        if (childrenElement != null)
                        {
                            var acmsChildren = Acms.Bll.TemplateHierarchy.GetAllByParentId(acmsTemplate.Id);
                            var i = 0;
                            foreach (var name in childrenElement.Elements("child").Select(x => x.Attribute("name") != null ? x.Attribute("name").Value : null))
                            {
                                if (!string.IsNullOrEmpty(name))
                                {
                                    var acmsChild = acmsChildren.Where(x => x.ChildName == name).FirstOrDefault();
                                    if (acmsChild == null)
                                    {
                                        var newChild = currentTemplates.Where(x => x.Name == name).FirstOrDefault();
                                        if (newChild != null)
                                        {
                                            AddToLog("Creating Child '{0}' for '{1}'", name, acmsTemplate.Name);
                                            acmsChild = Acms.Bll.TemplateHierarchy.CreateInstance();
                                            acmsChild.ChildId = newChild.Id;
                                            acmsChild.ParentId = acmsTemplate.Id;
                                            acmsChild.Sequence = i;
                                            acmsChild.UseTransaction(acmsTemplate.TransactionKey);
                                            acmsChildren.Add(acmsChild);
                                            acmsChild.Update();
                                        }
                                    }
                                    else
                                    {
                                        AddToLog("could not find template {0} to add as child for {1}", name, acmsTemplate.Name);
                                    }
                                }
                                else
                                {
                                    AddToLog("child element {0} for template {1} had no name attribute", i, acmsTemplate.Name);
                                }
                                i++;
                            }
                        }
                        else
                        {
                            AddToLog("No 'children' element for {0}", acmsTemplate.Name);
                        }
                    }
                }
                catch
                {
                    AddToLog("Rolling Back {0}", nameAttribute.Value);
                    acmsTemplate.RollbackTransaction();
                    throw;
                }
                finally
                {
                    if (acmsTemplate.TransactionKey != Guid.Empty)
                    {
                        AddToLog("Commmiting {0}", nameAttribute.Value);
                        acmsTemplate.CommitTransaction();
                    }
                }
            }
        }
    }

    /// <summary>
    /// Uploads Template Files settings from template xml node
    /// </summary>
    /// <param name="template">template xml node</param>
    /// <param name="acmsTemplate">Acms Template</param>
    private void UploadFilesSettings(System.Xml.Linq.XElement template, Acms.Bll.Template acmsTemplate, List<Acms.Bll.TemplateFile> acmsFiles)
    {
        var filesElement = template.Element("files");
        if (filesElement != null)
        {
            var files = filesElement.Elements("file").ToList();
            foreach(var file in files)  
            {
                var nameAttribute = file.Attribute("name");
                var pathAttribute = file.Attribute("path");
                var defaultAttribute = file.Attribute("default");

                if (nameAttribute != null && !string.IsNullOrEmpty(nameAttribute.Value))
                {
                    var save = false;
                    var acmsFile = acmsFiles.Where(x => x.Name == nameAttribute.Value).FirstOrDefault();
                    if (acmsFile == null)
                    {
                        AddToLog("Creating file {0} for template {1}", nameAttribute.Value, acmsTemplate.Name);
                        acmsFile = Acms.Bll.TemplateFile.CreateInstance(acmsTemplate, nameAttribute.Value);
                        save = true;
                    }
                    else
                    {
                        AddToLog("Found file {0} for template {1}", nameAttribute.Value, acmsTemplate.Name);
                    }
                    if (defaultAttribute != null)
                    {
                        if (defaultAttribute.Value.ToLower() == "true" && !acmsFile.IsDefault)
                        {
                            save = true;
                            acmsFile.IsDefault = true;
                        }
                        else if (defaultAttribute.Value.ToLower() != "true" && acmsFile.IsDefault)
                        {
                            save = true;
                            acmsFile.IsDefault = false;
                        }

                    }
                    if (pathAttribute != null && !pathAttribute.Value.Equals(acmsFile.Path, StringComparison.InvariantCultureIgnoreCase))
                    {
                        save = true;
                        acmsFile.Path = pathAttribute.Value;
                    }

                    if (save)
                    {
                        AddToLog("Saving File {0} for {1}", acmsFile.Name, acmsTemplate.Name);
                        acmsFile.UseTransaction(acmsTemplate.TransactionKey);
                        acmsFile.Update();
                    }
                }
                else
                {
                    AddToLog("No name attribute for file {0} in template {1}", files.IndexOf(file), acmsTemplate.Name);
                }
            }
        }
        else
        {
            AddToLog("No 'files' element for {0}", acmsTemplate.Name);
        }
    }

    /// <summary>
    /// Uploads the control settings for a templates from tempalte xml node
    /// </summary>
    /// <param name="template"></param>
    /// <param name="acmsTemplate"></param>
    /// <param name="acmsControlTypes"></param>
    private void UploadControlSettings(System.Xml.Linq.XElement template, Acms.Bll.Template acmsTemplate, List<Acms.Bll.TemplateControl> acmsControls, List<Acms.Bll.ControlType> acmsControlTypes)
    {
        var controlsElement = template.Element("controls");
        if (controlsElement != null)
        {
            var controls = controlsElement.Elements("control").ToList();
            var i = 0;
            foreach(var control in controls)  
            {
                var nameAttribute = control.Attribute("name");
                var typeAttribute = control.Attribute("type");
                var notesNode = control.Element("notes");
                if (nameAttribute != null && !string.IsNullOrEmpty(nameAttribute.Value))
                {
                    var save = false;
                    var acmsControl = acmsControls.Where(x => x.Name == nameAttribute.Value).FirstOrDefault();
                    if (acmsControl == null)
                    {
                        acmsControl = Acms.Bll.TemplateControl.CreateInstance();
                        acmsControl.TemplateId = acmsTemplate.Id;
                        acmsControl.Name = nameAttribute.Value;
                    }

                    if (typeAttribute != null)
                    {
                        int tmpControlTypeId = FindControlTypeId(typeAttribute, acmsControlTypes);
                        if (tmpControlTypeId > 0 && acmsControl.TypeId != tmpControlTypeId)
                        {
                            save = true;
                            acmsControl.TypeId = tmpControlTypeId;
                        }
                        else if(tmpControlTypeId == 0)
                        {
                            AddToLog("Failed to find type '{0}' for control '{1}' in templates '{2}' so skipping control", typeAttribute.Value, acmsControl.Name, acmsTemplate.Name);
                            continue;
                        }
                    }
                    else
                    {
                        AddToLog("Template control {0} in template {1}", i, acmsControl.Name, acmsTemplate);
                    }

                    if (acmsControl.Sequence != i)
                    {
                        save = true;
                        acmsControl.Sequence = i;
                    }

                    if (notesNode != null && acmsControl.Notes != notesNode.Value)
                    {
                        save = true;
                        acmsControl.Notes = notesNode.Value;
                    }

                    if (save)
                    {
                        AddToLog("Saving Control {0} for {1}", acmsControl.Name, acmsTemplate.Name);
                        acmsControl.UseTransaction(acmsTemplate.TransactionKey);
                        acmsControl.Update();
                    }
                }
                else
                {
                    AddToLog("No name attribute for control {0} in template {1}", i, acmsTemplate.Name);
                }
                i++;
            }
        }
        else
        {
            AddToLog("No 'controls' element for {0}", acmsTemplate.Name);
        }
    }

    private int FindControlTypeId(System.Xml.Linq.XAttribute typeAttribute, List<Acms.Bll.ControlType> acmsControlTypes)
    {
        if(typeAttribute == null)
            throw new ArgumentNullException("typeAttribute");
        if(acmsControlTypes == null)
            throw new ArgumentNullException("acmsControlTypes");

        //name match
        Acms.Bll.ControlType tmp = acmsControlTypes.Where(x => x.Name.Equals(typeAttribute.Value, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

        //front end control fully qualified match
        if (tmp == null)
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Equals(typeAttribute.Value, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        //front end control name match
        if (tmp == null)
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Substring(x.FrontEndControlType.LastIndexOf(".") + 1).Equals(typeAttribute.Value, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

        if (tmp == null)
        {
            var tmpFrontEndTypes = acmsControlTypes.Select(x => Page.LoadControl(System.Type.GetType(x.FrontEndControlType, true, true), null)).ToList();
            if (typeAttribute.Value.Equals("AcmsHtml", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.HtmlContentControlDisplay>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsImage", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.ImageContentControlDisplay>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsDownloadableFile", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.ContentControls.FrontEnd.DownloadableFileContentControl>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsFloatingImage", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.ContentControls.FrontEnd.FloatingImageContentControl>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsRelatedPosts", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.ContentControls.FrontEnd.RelatedPostsContentControl>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsFlash", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.FlashContentControlDisplay>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsPdf", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.PdfContentControlDisplay>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsText", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.TextContentControlDisplay>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }
            else if (typeAttribute.Value.Equals("AcmsFlashVideo", StringComparison.InvariantCultureIgnoreCase))
            {
                var tmpControl = tmpFrontEndTypes.OfType<Acms.AcmsControls.ContentControls.FrontEnd.FlashVideoContentControl>().FirstOrDefault();
                tmp = acmsControlTypes[tmpFrontEndTypes.IndexOf(tmpControl)];
            }

          
        }

        /*if (tmp == null && typeAttribute.Value.Equals("AcmsHtml", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Substring(0, x.FrontEndControlType.IndexOf(",")).Equals(typeof(Acms.AcmsControls.HtmlContentControlDisplay).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
        else if (tmp == null && typeAttribute.Value.Equals("AcmsImage", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Substring(0, x.FrontEndControlType.IndexOf(",")).Equals(typeof(Acms.AcmsControls.ImageContentControlDisplay).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
        else if (tmp == null && typeAttribute.Value.Equals("AcmsDownloadableFile", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Equals(typeof(Acms.AcmsControls.ContentControls.FrontEnd.DownloadableFileContentControl).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
        else if (tmp == null && typeAttribute.Value.Equals("AcmsFloatingFile", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Equals(typeof(Acms.AcmsControls.ContentControls.FrontEnd.FloatingImageContentControl).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
        else if (tmp == null && typeAttribute.Value.Equals("AcmsRelatedPosts", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Equals(typeof(Acms.AcmsControls.ContentControls.FrontEnd.RealatedPostsContentControl).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
        else if (tmp == null && typeAttribute.Value.Equals("AcmsFlash", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Equals(typeof(Acms.AcmsControls.FlashContentControlDisplay).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
        else if (tmp == null && typeAttribute.Value.Equals("AcmsPdf", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Equals(typeof(Acms.AcmsControls.PdfContentControlDisplay).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
        else if (tmp == null && typeAttribute.Value.Equals("AcmsText", StringComparison.InvariantCultureIgnoreCase))
        {
            tmp = acmsControlTypes.Where(x => x.FrontEndControlType.Equals(typeof(Acms.AcmsControls.ImageContentControlDisplay).FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }*/

        return tmp != null ? tmp.Id : 0;
    }

    void tree_NodeClick(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
    {
        if (System.IO.File.Exists(e.Node.Value))
        {
            lbl.Text = string.Format("Selected {0}", e.Node.Value);
            UploadSettings(e.Node.Value);
        }
        else
        {
            lbl.Text = "Cannot select a folder";
        }
    }

    void tree_NodeExpand(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
    {
        AddNodes(e.Node);
    }

    public override void DataBind()
    {
        string root = Server.MapPath("~/..");
        string name = GetDisplayName(root);

        var rootNode = new Telerik.Web.UI.RadTreeNode(name, root);
        tree.Nodes.Add(rootNode);
        AddNodes(rootNode);
    }

    private void AddNodes(Telerik.Web.UI.RadTreeNode node)
    {
        node.ExpandMode = Telerik.Web.UI.TreeNodeExpandMode.ClientSide;
        node.Expanded = true;

        var files = System.IO.Directory.GetFiles(node.Value, "*.xml");
        var directories = System.IO.Directory.GetDirectories(node.Value);

        var fileNodes = files.Select(x => new Telerik.Web.UI.RadTreeNode(GetDisplayName(x), x) { ExpandMode = Telerik.Web.UI.TreeNodeExpandMode.ClientSide, Expanded = true });
        node.Nodes.AddRange(fileNodes);

        var directoryNodes = directories.Select(x => new Telerik.Web.UI.RadTreeNode(GetDisplayName(x), x) { ExpandMode = Telerik.Web.UI.TreeNodeExpandMode.ServerSideCallBack, Expanded = false});
        node.Nodes.AddRange(directoryNodes);
    }

    private string GetDisplayName(string path)
    {
        if (path.EndsWith("\\"))
            path = path.Substring(0, path.Length - 1);

        return path.Substring(path.LastIndexOf("\\") + 1);
    }

    public override void GetBreadCrumbs(BaseMasterPage.BreadCrumbCollection breadcrumbs)
    {
        base.GetBreadCrumbs(breadcrumbs);
        breadcrumbs.Add("Upload Settings", AcmsContext.OriginalUrl);
    }
}
